/**
 *  @author cainli
 *  @d2013-4-19 @tim上午11:49:03
 */
package com.cainli.szbus.data.operation;

import java.util.HashMap;

import android.content.Context;
import android.os.Bundle;

import com.cainli.szbus.config.WSConfig;
import com.cainli.szbus.log.CLog;
import com.foxykeep.datadroid.exception.ConnectionException;
import com.foxykeep.datadroid.exception.DataException;
import com.foxykeep.datadroid.network.NetworkConnection;
import com.foxykeep.datadroid.network.NetworkConnection.ConnectionResult;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.service.RequestService.Operation;

/**
 * @author cainli
 * 
 */
public abstract class BaseOperation implements Operation {
	private static final String TAG = BaseOperation.class.getSimpleName();
	public static final String PARAM_RETURN_FORMAT = "com.cainli.szbus.returnFormat";
	private int RETURN_FORMAT_XML = 0;
	private int RETURN_FORMAT_JSON = 1;
	private int returnFormat;
	protected HashMap<String, String> params = new HashMap<String, String>();
	private Bundle bundleResult;
	@Override
	public Bundle execute(Context context, Request request)
			throws ConnectionException, DataException {
		returnFormat = request.getInt(PARAM_RETURN_FORMAT);
		initParams(request);
		NetworkConnection networkConnection = new NetworkConnection(context,
				getUrl());
		ConnectionResult connResult = networkConnection.execute();
		doResult(context,connResult);
		return  bundleResult;
	}
	
	private void doResult(Context context, ConnectionResult connresult){
		bundleResult = getParseResult(connresult);
		addDB(context, bundleResult);
	}


	protected String getUrl() {
		StringBuffer url = new StringBuffer(WSConfig.ROOT_URL);
		url.append("/").append(getType()).append("?").append("app_key=")
				.append(WSConfig.APP_KEY);
		for (String key : params.keySet()) {
			url.append("&");
			url.append(key).append("=").append(params.get(key));
		}
		if (isJson()) {
			url.append("&alt=json");
		}
		CLog.d(TAG, url.toString());
		return url.toString();
	}

	public boolean isJson() {
		return returnFormat == RETURN_FORMAT_JSON;
	}

	public boolean isXml() {
		return returnFormat == RETURN_FORMAT_XML;
	}
	
	public void addDB(Context context, Object object){
		//XXX:子类继承
	};
	
	protected abstract String getType();
	
	protected abstract void initParams(Request request);
	
	protected abstract Bundle getParseResult(ConnectionResult result);
}
